package com.feeyo.monitor.service.imp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.feeyo.monitor.utils.DeptTreeNode;
import com.feeyo.monitor.utils.TreeNodeUtil;
import org.postgresql.util.PSQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.feeyo.monitor.domain.Department;
import com.feeyo.monitor.mapper.DepartmentMapper;
import com.feeyo.monitor.service.DepartmentService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DepartmentServiceImp implements DepartmentService {

	@Autowired
	DepartmentMapper departmentMapper;

	@Override
	public List<Department> selectByPage(Map param) {
	    return departmentMapper.selectByPage(param);
	}
    //加载递归节点逻辑更改
    @Override
    public List<DeptTreeNode> selectByTree(Map param,String parentid) {
        List<Department> result = departmentMapper.selectByPage(param);
        if (result.size() >0){
            if (!parentid.equals("")){
                result.forEach(item->{
                    if (item.getId().equals(parentid)){
                        item.setParentid(null);
                    }
                });
            }
        }

        List<DeptTreeNode> treeGrid = TreeNodeUtil.buildTree(result);
        System.out.println("treeGrid->"+treeGrid.size());
        //String jsonStr = JSON.toJSON(treeGrid).toString();
        return treeGrid;
    }


    @Override
	public Department selectByPrimaryKey(String id)  throws PSQLException{
		return departmentMapper.selectByPrimaryKey(id);
	}


	@Override
    @Transactional
	public int updateDeleteStatus(String deptId) {
        departmentMapper.updateChildDeleteStatus(deptId);
        return departmentMapper.updateDeleteStatus(deptId);
	}

	@Override
	public int insert(Department record) {
		return departmentMapper.insert(record);
	}

	@Override
	public int updateByPrimaryKeySelective(Department record) {
		return departmentMapper.updateByPrimaryKeySelective(record);
	}

    @Override
    public int updateChildDeleteStatus(String parentId) {
        return departmentMapper.updateChildDeleteStatus(parentId);
    }

    @Override
    public List<String> selectTreeNode(String depId) {
        return departmentMapper.selectTreeNode(depId);
    }

    @Override
    public String selectIdByDept1(String name) {
        return departmentMapper.selectIdByDept1(name);
    }

    @Override
    public String selectIdByDept1AndDept2(String name, String parentid) {
        return departmentMapper.selectIdByDept1AndDept2(name,parentid);
    }
}
